<template>
	<div id='page__goods'>
		<div
			v-if="showHot"
			class="carousel-container">
			<el-carousel
				type="card"
				trigger="click"
				:autoplay="false"
				height="200px">
				<el-carousel-item
					v-for="(item, index) in hotList"
					:key="item.id"
				>
					<div class="carousel-item" @click="goGoodsDetail(item)">
						<el-image
							fit="cover"
							:src="item.img"></el-image>
						<div class="goods-summary">
							<p class="goods-title">{{item.name}}</p>
							<div
								style="display: flex;flex-direction: row;width: 100%;justify-content: space-between;align-items: center">
								<p class="goods-sellCount">已售 {{item.sellCount}}</p>
								<p class="goods-price">¥ {{item.price}}</p>
							</div>
						</div>
						<div class="rank">
							<span class="el-badge__content" :class="['badge-' + (index + 1)]">
								<span style="margin-left: 6px">HOT</span>
								<span style="padding: 0 6px">{{index + 1}}</span>
							</span>
						</div>
					</div>
				</el-carousel-item>
			</el-carousel>
		</div>

		<div
			:style="{marginTop: !showHot ? '16px':''}"
			class="goods-list"
			v-loading="loading && form.page === 1"
		>
			<div class="goods-header">
				<div class="header__main">
					<span style="font-size: 12px; color: #666">{{filter}}</span>
				</div>
				<div class="header__sub">
					共 {{total}} 个商品
				</div>
			</div>
			<div class="goods-main">
				<el-row :gutter="16">
					<el-col
						v-for="item in goodsList"
						:key="item.key"
						:span="6"
					>
						<el-card shadow="hover">
							<div slot="header" class="clearfix">
								<div
									v-if="item.status === GOODS_INVALID"
									class="is-invalid">
									<div class="goods-invalid">
										<span>已下架</span>
									</div>
								</div>
								<el-image
									:src="item.img"
									fit="contain"
								>
								</el-image>
							</div>
							<h3 class="goods-title">{{item.name}}</h3>
							<p class="goods-price">¥ {{item.price}}</p>
							<div class="goods-sub">
								<p class="goods-sellCount">已售 {{item.sellCount}}</p>
								<div>
									<template v-if="isAdmin">
										<el-button
											size="mini"
											icon="el-icon-edit"
											@click="$router.push('/goods/edit?id=' + item.id)"
										>
										</el-button>
										<el-button
											type="danger"
											size="mini"
											icon="el-icon-delete"
											@click="deleteGoods(item)"
										>
										</el-button>
									</template>
									<el-button
										v-else
										type="warning"
										size="mini"
										icon="el-icon-s-goods"
										@click="goGoodsDetail(item)"
									>
									</el-button>
								</div>
							</div>
						</el-card>
					</el-col>
				</el-row>
				<p class="no-more">{{loading && form.page > 1 ? '正在加载...' : loadEnd ? '没有更多了～' : '下拉获取更多'}}</p>
			</div>
		</div>
	</div>
</template>

<script>
  /**
   *
   *
   *
   */
  import {mapState, mapGetters} from 'vuex'
  import * as CONSTANT from '../../config/constant'

  export default {
    name: "list",
    props: {
      isAdmin: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        ...CONSTANT,
        form: {
          categoryId: 0,
          minPrice: '',
          maxPrice: '',
          keyword: '',
          page: 1,
          size: 12//CONSTANT.PAGE_SIZE
        },
        goodsList: [],
        total: 0,
        loading: false,
        isFocus: false
      }
    },
    computed: {
      ...mapState([
        'categories',
        'hotList',
        'userInfo'
      ]),
      showHot() {
        let {minPrice, maxPrice, keyword, categoryId} = this.form
        return !this.isAdmin && !minPrice && !maxPrice && !keyword && !categoryId
      },
      filter() {
        let categories = this.categories
        let {keyword, categoryId, minPrice, maxPrice} = this.form
        let texts = []
        if (keyword || categoryId || minPrice || maxPrice) {
          if (!!keyword) {
            texts.push('关键词：' + keyword)
          }
          if (categoryId) {
            let category = categories.find(item => ('' + item.id) === ('' + categoryId))
            if (category) {
              let parentName = ''
              console.log(category)
              if (category.parentId) {
                let parent = categories.find(item => ('' + item.id) === ('' + category.parentId))
                parentName = parent && parent.name
              }
              let names = [category.name]
              if (parentName) {
                names.unshift(parentName)
              }
              texts.push(`类别：${names.join(' / ')}`)
            }
          }
          if (minPrice && maxPrice) {

            minPrice = parseFloat(minPrice)
            maxPrice = parseFloat(maxPrice)
            let temp
            if (maxPrice < minPrice) {
              temp = maxPrice
              maxPrice = minPrice
              minPrice = temp
            }
            texts.push(`价格区间：¥${minPrice} ~ ¥${maxPrice}`)
          } else if (minPrice) {
            texts.push(`价格高于 ¥${minPrice} 元`)
          } else if (maxPrice) {
            texts.push(`价格低于 ¥${maxPrice} 元`)
          }
        } else if (categoryId === 0 || categoryId === '0') {
          texts.push('以下为推荐商品')
        } else {
          texts.push('以下为全部商品')
        }

        return texts.join('；')
      },
      loadEnd() {
        return this.total <= this.goodsList.length
      }
    },
    watch: {
      $route: {
        deep: true,
        immediate: true,
        handler({query}) {
          this.form.minPrice = query.minPrice || ''
          this.form.maxPrice = query.maxPrice || ''
          this.form.categoryId = query.categoryId !== undefined ? query.categoryId : this.isAdmin ? '' : 0
        }
      }
    },
    mounted() {
      if (!this.isAdmin) {
        this.$store.dispatch('getHotList')
      }
      this.getList(false)
      this.$bus.$on('infinite-scroll', () => {
        if (this.loading) return false
        if (this.loadEnd) return false
        this.form.page += 1
        this.getList(true)
      })
      this.$bus.$on('getGoodsList', (keyword) => {
        if (keyword !== undefined) {
          this.form.keyword = keyword
        }
        this.form.page = 1
        this.getList(false)
      })
    },
    beforeDestroy() {
      this.$bus.$off('infinite-scroll')
      this.$bus.$off('getGoodsList')
    },
    methods: {
      goGoodsDetail(item) {
        if (this.isAdmin) return
        this.$router.push({
          path: '/goods/detail',
          query: {
            id: item.id
          }
        })
      },
      getList(abort) {
        if (this.loading && abort) return false
        this.loading = true
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          let params = {
            ...this.form
          }
          let goodsList = this.goodsList,
            total = this.total
          if (params.page === 1) {
            goodsList = []
            total = 0
          }

          this.$axios.post('/goods/list', params, {
              abort: true
            })
            .then(({success, message, data}) => {
              if (success) {
                if (params.page === 1) {
                  goodsList = data.content
                } else {
                  goodsList = goodsList.concat(data.content)
                }
                total = data.total || 0
              } else {
                this.$message({
                  type: 'error',
                  message: message
                })
              }
            })
            .catch(({message}) => {
              this.$message({
                type: 'error',
                message: message
              })
            })
            .finally(() => {
              this.loading = false
              this.goodsList = goodsList
              this.total = total
            })
        }, 200)
      },
      deleteGoods(goods) {
        this.$confirm(`确认删除 ${goods.name} ?`, '删除商品', {
          beforeClose: (action, instance, done) => {
            if (action !== 'confirm') {
              done()
              return false
            }
            this.$axios.get("/goods/delete", {
                params: {
                  id: goods.id
                }
              })
              .then(({success, message}) => {
                if (success) {
                  this.$message({
                    type: 'success',
                    message: '删除成功'
                  })
                  this.getList(true)
                } else {
                  this.$message({
                    type: 'error',
                    message: message
                  })
                }
              })
              .catch(({message}) => {
                this.$message({
                  type: 'error',
                  message: message
                })
              })
              .finally(() => {
                done()
              })
          }
        })
      },
    },
  }
</script>

<style lang='less'>

	#page__goods {
		flex-grow: 1;
		flex-shrink: 1;
		display: flex;
		flex-direction: column;

		.carousel-container {
			width: 100%;
			margin-top: 20px;
			border-radius: 6px;
			overflow: hidden;
			/*background-color: #fff;*/

			.el-carousel__item {
				background-color: transparent;

				&.is-active {
					box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .3);
				}


				.carousel-item {
					width: 100%;
					height: 100%;
					position: relative;
					display: flex;
					flex-direction: row;

					.el-image {
						height: 100%;
						flex-shrink: 1;
						flex-grow: 1;

						.el-image__inner {
							height: 100%;
							width: 100%;
							max-width: 100%;
							max-height: 100%;
						}
					}

					.goods-summary {
						flex-shrink: 0;
						flex-grow: 0;
						width: 140px;
						display: inline-flex;
						flex-direction: column;
						justify-content: flex-end;
						align-items: flex-end;
						padding: 20px;
						background-color: #fff;

						.goods-title {
							color: rgba(0, 0, 0, .85);
							font-size: 16px;
							font-weight: normal;
							margin: 0 0 12px 0;
							min-height: 44px;
						}

						.goods-price {
							font-size: 13px;
							color: #999;
							margin: 0;
							line-height: 1;
						}

						.goods-sellCount {
							font-size: 13px;
							color: #999;
							margin: 0;
						}
					}
				}

				.rank {
					position: absolute;
					right: 0;
					top: 10px;
					height: 22px;
					width: 20%;
					display: flex;
					justify-content: flex-end;
					align-items: center;

					.el-badge__content {
						border-top-right-radius: 0;
						border-bottom-right-radius: 0;
						border: none;
						line-height: 24px;
						height: 24px;
						background: linear-gradient(49deg, #d3bf99, #e0cfb1);

						&.badge-1 {
							background: linear-gradient(49deg, #dd1d1d, #f84141);;
						}

						&.badge-2 {
							background: linear-gradient(49deg, #ff732c, #ff9d5d);
						}

						&.badge-3 {
							background: linear-gradient(49deg, #ffb535, #ffcb3a);
						}
					}
				}
			}
		}

		.goods-list {
			margin-top: 0;
			padding: 0;
			flex-grow: 1;
			flex-shrink: 1;
		}

		.goods-header {
			display: flex;
			flex-direction: row;
			align-items: center;
			flex-wrap: nowrap;
			border-bottom: 1px solid #eee;
			padding: 12px 20px;
			background-color: #fff;

			.el-input {
				width: 160px;
				transition: width 0.3s;

				&.is-active {
					width: 260px;
				}
			}
		}

		.header__main {
			flex-grow: 1;
			flex-shrink: 1;
		}

		.header__sub {
			flex-grow: 0;
			flex-shrink: 0;
			color: #999;
			font-size: 12px;
		}


		.goods-main {
			.el-col {
				margin-top: 20px;
			}

			.el-card__header {
				padding: 0;
				line-height: 1;

				.clearfix {
					width: 100%;
					padding-top: 60%;
					position: relative;

					.is-invalid {
						position: absolute;
						left: 0;
						top: 0;
						z-index: 10;
						width: 100%;
						height: 100%;
						background-color: rgba(0, 0, 0, 0.5);
						display: flex;
						align-items: center;
						justify-content: center;

						.goods-invalid {
							transform: rotate(-35deg);
							color: #fff;
						}
					}

				}

				.el-image {
					position: absolute;
					left: 0;
					top: 0;
					z-index: 9;
					width: 100%;
					height: 100%;
				}
			}

			.el-card__body {
				padding: 20px 16px;
			}

			.el-image {
				width: 100%;

				.image-slot {
					width: 100%;
					height: 100%;
					display: flex;
					align-items: center;
					justify-content: center;
					background-color: #f0f2f5;
					border-radius: 4px;

					.el-icon-picture-outline {
						font-size: 30px;
						color: #999;
					}
				}
			}

			.goods-title {
				color: rgba(0, 0, 0, .85);
				font-size: 16px;
				font-weight: normal;
				margin: 0;
				height: 44px;
				overflow: hidden;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				text-overflow: ellipsis;
			}

			.goods-price {
				font-size: 13px;
				color: #999;
				margin: 6px 0;
				line-height: 1;
			}

			.goods-sub {
				display: flex;
				flex-direction: row;
				align-items: center;
				height: 32px;

				.goods-sellCount {
					flex-grow: 1;
					flex-shrink: 1;
					font-size: 13px;
					color: #999;
					margin: 0;
				}

				.el-button {
					flex-grow: 0;
					flex-shrink: 0;
				}
			}
		}

		.no-more {
			text-align: center;
			color: #999;
			font-size: 12px;
			padding: 20px;
			margin: 0;
		}

		.el-input-number--small {
			width: 100px;
			line-height: 28px;

			.el-input-number__decrease, .el-input-number__increase {
				line-height: 26px;
				width: 26px;
			}

			.el-input--small {
				line-height: 28px;
			}

			.el-input__inner {
				line-height: 26px;
				height: 28px;
			}
		}
	}
</style>
